import 'package:flutter/material.dart';

typedef OnDoubleTap(TapDownDetails details);
typedef OnHorizontalDragStart(DragStartDetails details);
typedef OnHorizontalDragUpdate(DragUpdateDetails details);
typedef OnHorizontalDragEnd(DragEndDetails details);

class GestureListener extends StatelessWidget {
  final Widget child;
  final OnDoubleTap onDoubleTap;
  final OnHorizontalDragStart onHorizontalDragStart;
  final OnHorizontalDragUpdate onHorizontalDragUpdate;
  final OnHorizontalDragEnd onHorizontalDragEnd;

  GestureListener(
      {Key key,
      @required this.child,
      @required this.onDoubleTap,
      this.onHorizontalDragStart,
      this.onHorizontalDragUpdate,
      this.onHorizontalDragEnd})
      : super(key: key);

  static int _lastTapDownTime = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: child,
      onTapDown: _onTapDown,
      onHorizontalDragStart: _onHorizontalDragStart,
      onHorizontalDragUpdate: _onHorizontalDragUpdate,
      onHorizontalDragEnd: _onHorizontalDragEnd,
    );
  }

  // 只判断了双击时间间隔，没有判断位置是否够小
  void _onTapDown(TapDownDetails details) {
    int currentTapTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTapTime - _lastTapDownTime > 0 &&
        currentTapTime - _lastTapDownTime <= 200) {
      _lastTapDownTime = 0;
      onDoubleTap?.call(details);
      return;
    }
    _lastTapDownTime = DateTime.now().millisecondsSinceEpoch;
  }

  void _onHorizontalDragStart(DragStartDetails details) {
    onHorizontalDragStart?.call(details);
  }

  void _onHorizontalDragUpdate(DragUpdateDetails details) {
    onHorizontalDragUpdate.call(details);
  }

  void _onHorizontalDragEnd(DragEndDetails details) {
    onHorizontalDragEnd.call(details);
  }
}
